package com.exm.mqttservice;

import com.exm.service.DataService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Random;

@Component
@Order(1)
public class MqttProducer {

    private static final String BROKER = "tcp://47.98.117.180:1883";
    private static final String TOPIC = "sensor/data";

    private static final String USERNAME = "root"; // 设置用户名
    private static final String PASSWORD = "2583549902@qq.com"; // 设置密码

    private MqttClient mqttClient;

    @Autowired
    private DataService dataService;

    public MqttProducer() throws Exception {
        // 创建 MQTT 客户端
        this.mqttClient = new MqttClient(BROKER, MqttClient.generateClientId());

        // 设置连接选项
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(USERNAME); // 设置用户名
        options.setPassword(PASSWORD.toCharArray()); // 设置密码

        // 连接到 MQTT Broker
        mqttClient.connect(options);
    }

    @Scheduled(fixedRate = 100000) // 每100秒发送一次数据
    public void publishData() {
        Random random = new Random();
        double value = Math.round(random.nextDouble() * 1 * 100.0) / 100.0; // 生成0到0.9之间的随机小数
        String payload = "{\"data\":" + value + "}";

        try {
            MqttMessage message = new MqttMessage(payload.getBytes());
            mqttClient.publish(TOPIC, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
